<?php
namespace Services;
/**
 * File holds class for business data manipulation
 *
 * PHP version 5.3.5
 *
 * @category   CM
 * @package    Services
 * @subpackage -
 * @author     markus karileet <markuskarileet@hotmail.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @link       -
 */
class Business extends ORM {
	/**
	 * Method searches DB for business with code and returns it when found
	 * @param var $code Business code
	 * @return \Entities\Business on success, false on error
	 */
	public function getBusinessByCode($code) {
		$business = new \Entities\Business();
		$business->setCode($code);
		$b = false;
		try {
			$b = $this->select($business);
		} catch (\Exception $e) {
			//TODO: do not eat
		}
		return $b;
	}
	
	/**
	 * Method inserts new business by code. Theese businesses need to be updated
	 * and a correct name should be entered as well as other params
	 */
	public function insertTemplate($code) {
		$business = new \Entities\Business();
		$business->setCode($code);
		$business->setName(ucfirst($code));
		$business->setDescription('TODO!');
		$id = $this->insert($business);
		$business->setId($id);
		return $business;
	}
	
	/**
	 * Method calculates Net Promoter Score
	 * @param array $ratings Array of Rating objects
	 * @return float NPS score
	 */
	public function calculateNps(array $ratings) {
		$totalNumber = count($ratings);
		$detractors = 0;
		$promoters = 0;
		foreach (array_keys($ratings) as $itr) {
			//read total number of promoters / detractors to get NPS
			if ($ratings[$itr]->getRating() >= \Enum\NPS::Promoters) {
				$promoters++;
			} else if ($ratings[$itr]->getRating() < \Enum\NPS::Passive) {
				$detractors++;
			}
		}
	
		//calculate percentages for NPS calculation
		$percentageOfPromoters = $promoters * 100 / $totalNumber;
		$percentageOfDetractors = $detractors * 100 / $totalNumber;
		// return NPS = percentage of promoters - percentage of detractors
		return $percentageOfPromoters - $percentageOfDetractors;
	}
}